﻿/*******************************************************************************
* Copyright (C) JuCheap
* 
* Author: JuCheap
* Create Date: 2019/12/26 11:21:05
* Description: <Description>
* 
* Revision History:
* Date         Author               Description
*
*********************************************************************************/

using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.IRepository;
using JuCheap.Core.IService;
using JuCheap.Core.Model;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JuCheap.Core.Service
{
    /// <summary>
    /// 升级日志查询服务
    /// </summary>
    public class SysUpgradeLogQueryService : ISysUpgradeLogQueryService
    {
        private readonly ISysUpgradeLogRepository _sysUpgradeLogRepository;
        private readonly ISysUpgradeLogDetailRepository _sysUpgradeLogDetailRepository;

        /// <summary>
        /// ctor
        /// </summary>
        public SysUpgradeLogQueryService(ISysUpgradeLogRepository sysUpgradeLogRepository, ISysUpgradeLogDetailRepository sysUpgradeLogDetailRepository)
        {
            _sysUpgradeLogRepository = sysUpgradeLogRepository;
            _sysUpgradeLogDetailRepository = sysUpgradeLogDetailRepository;
        }

        /// <summary>
        /// 查询最近的100条升级日志
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<UpgradeLogResponseDto>> QueryTopAsync()
        {
            var logQuery = from log in _sysUpgradeLogRepository.Queryable(false).OrderByDescending(x => x.CreateTime)
                           select new UpgradeLogResponseDto
                           {
                               Id = log.Id,
                               Title = log.Title,
                               UpgradeDate = log.UpgradeDate,
                               Version = log.Version
                           };
            var logs = await logQuery.Skip(0).Take(100).ToListAsync();
            if (logs.AnyOne())
            {
                var logIds = logs.Select(x => x.Id).ToList();
                var detailQuery = from detail in _sysUpgradeLogDetailRepository.Queryable(false)
                                  where logIds.Contains(detail.LogId)
                                  select new SysUpgradeLogDetailDto
                                  {
                                      LogId = detail.LogId,
                                      Detail = detail.Detail
                                  };
                var details = await detailQuery.ToListAsync();
                foreach (var log in logs)
                {
                    log.Details = details.Where(x => x.LogId == log.Id).Select(x => x.Detail).ToList();
                }
            }

            return logs;
        }
    }
}
